﻿using System;
using System.Collections.Generic;
using System.Text;
using jade.core.behaviours;
using MarketSimulator.Utils.Attributes;
using jade.lang.acl;
using MarketSimulator.Utils.Communication;

namespace MarketSimulator.Agents.Behaviors
{
    /// <summary>
    /// Storage Behavior
    /// </summary>
    public class StorageBehavior : CyclicBehaviour
    {
        StorageAttributes Attributes;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="attributes"></param>
        public StorageBehavior(StorageAttributes attributes) 
            : base(attributes.JadeAgent)
        {
            Attributes = attributes;
        }

        public override void action()
        {
            ACLMessage message = null;
            MessageTemplate pattern = MessageTemplate.MatchConversationId(Messages.CONVERSATION_ASK_DEPOSIT_OFFER);
            message = myAgent.receive(pattern);

            if (message != null)
            {
                string pInfo = GetDepositOffer(message.getContent());
                Attributes.WriteMessage("{0} asked for \"{1}\" storage offer. The price is {2}.", message.getSender().getLocalName(),
                    message.getContent(), pInfo);

                //Send message and required info
                ACLMessage reply = new ACLMessage();
                reply.addReceiver(message.getSender());
                reply.setConversationId(Messages.CONVERSATION_SAY_DEPOSIT_OFFER);
                reply.setContent(pInfo);
                myAgent.send(reply);
            }
            else
            {
                block();
            }
        }

        #region Private Methods

        private string GetDepositOffer(string message)
        {
            string[] parts = message.Split('|');
            int cityId = int.Parse(parts[0]);
            int quantityInt = int.Parse(parts[1]);

            if (quantityInt >= Attributes.StorageFacility.RemainingCapacity || cityId != Attributes.StorageFacility.Location)
            {
                return Messages.NOT_AVAILABLE;
            }
            else
            {
                return (quantityInt * Attributes.StorageFacility.CostPerUnit).ToString();
            }
        }

        #endregion

    }
}
